#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using Agresso.Interface.Layer.Domain;
using Agresso.Interface.Layer.Service;
using System.Collections;
using System.Web;

#endregion

namespace Agresso.Interface.Layer.Web
{
    public partial class UserControlUser : UserControl
    {
        User m_user;
        User m_current_user;
        UserService m_userService;
        EditMode m_editmode;
        MainForm m_mainForm;

        public UserControlUser(string name, User currentUser, MainForm mainForm)
        {
            InitializeComponent();
            initButtonEvent();
            this.Name = name;
            m_current_user = currentUser;
            m_mainForm = mainForm;
            m_userService = (UserService)ServiceFactory.Instance().GetService(ServiceFactory.USERSERVICE);
            initComboDataSource();
            //loadAllUser();
           // if (m_current_user.Role.RoleDetails[name].NewFlag)
                clearForm();
           // else
               // listViewRecords.SelectedIndex = listViewRecords.Items.Count > 0 ? 0 : -1;

        }

        private void initComboDataSource()
        {
            comboBoxRoleMaster.DataSource = m_userService.LoadAllRoleMaster();
        }

        private void setEditMode(EditMode editMode)
        {
            toolBarButtonSave.Enabled = (editMode == EditMode.Create || editMode == EditMode.Edit || editMode == EditMode.Saved || editMode == EditMode.Delete) && m_current_user.Role.RoleDetails[this.Name].NewFlag;
            toolBarButtonDelete.Enabled = (editMode == EditMode.Load) && m_current_user.Role.RoleDetails[this.Name].DeleteFlag;
            toolBarButtonEdit.Enabled = (editMode == EditMode.Load) && m_current_user.Role.RoleDetails[this.Name].UpdateFlag;
            toolBarButtonClear.Enabled = m_current_user.Role.RoleDetails[this.Name].UpdateFlag;
            m_editmode = editMode;
        }

        private void initButtonEvent()
        {
            toolBarButtonClear.Click += new EventHandler(toolBarButtonClear_Click);
            toolBarButtonSave.Click += new EventHandler(toolBarButtonSave_Click);
            toolBarButtonDelete.Click += new EventHandler(toolBarButtonDelete_Click);
            toolBarButtonRefresh.Click += new EventHandler(toolBarButtonRefresh_Click);
            toolBarButtonEdit.Click += new EventHandler(toolBarButtonEdit_Click);
            toolBarButtonSearch.Click += new EventHandler(toolBarButtonSearch_Click);
        }

        void toolBarButtonSearch_Click(object sender, EventArgs e)
        {
            UserSearchForm sch = new UserSearchForm(m_current_user, this);
            sch.ShowDialog();
        }

        void toolBarButtonEdit_Click(object sender, EventArgs e)
        {
            enableForm(true);
            setEditMode(EditMode.Edit);
        }

        void toolBarButtonRefresh_Click(object sender, EventArgs e)
        {
            //loadAllUser();
            initComboDataSource();
            if(m_editmode == EditMode.Load || m_editmode == EditMode.Edit )
                loadUser();
        }

        void toolBarButtonDelete_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Are you sure to delete this record?", "Confirmation", MessageBoxButtons.YesNo,
                MessageBoxIcon.Question, new EventHandler(DeleteConfirmation));
        }

        void DeleteConfirmation(object sender, EventArgs e)
        {
            try
            {
                MessageBoxWindow msg = (MessageBoxWindow)sender;
                if (msg.DialogResult == DialogResult.Yes)
                {
                    if (m_user.UserID > 0)
                    {
                        m_userService.DeleteUser(m_user);
                        MessageBox.Show("Record has been deleted.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                        clearForm();
                        //loadAllUser();
                        setEditMode(EditMode.Delete);
                    }
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error Exception", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }

        void toolBarButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (isValidForm())
                {
                    m_user.UserCode = textBoxUserCode.Text;
                    m_user.UserName = textBoxUserName.Text;
                    m_user.Password = textBoxPassword.Text;
                    m_user.ActiveCode = checkBoxActive.Checked;
                    m_user.EmailID = textBoxEmail.Text;
                    m_user.ExpiryDate = dateTimePickerExpiry.Value;
                    m_user.PasswordExpired = checkBoxPasswordExpired.Checked;
                    m_user.Role = (RoleMaster)comboBoxRoleMaster.SelectedItem;
                    m_user.CreatenBy = m_current_user.UserID;
                    m_user.ModificationBy = m_current_user.UserID;
                    m_user.ModificationTerminal = HttpContext.Current.User.Identity.Name.ToString() + "," + HttpContext.Current.Request.UserHostAddress;
                    if (m_user.UserID > 0)
                    {
                        m_userService.UpdateUser(m_user);
                    }
                    else
                    {
                        m_userService.InsertUser(m_user);
                    }
                    if (m_user.UserID == m_current_user.UserID)
                    {
                        m_mainForm.RefreshUserAndPermission(m_user);
                    }
                    MessageBox.Show("Record has been saved.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    clearForm();
                    //loadAllUser();
                    //setEditMode(EditMode.Saved);
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error Exception", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

        }

        private bool isValidForm()
        {
            clearErrorProvider();

            bool valid_a = textBoxUserCode.Text != string.Empty;
            bool valid_b = textBoxUserName.Text != string.Empty;
            bool valid_c = textBoxPassword.Text != string.Empty;
            bool valid_d = textBoxPassword.Text == textBoxConfirmPassword.Text;
            bool valid_e = comboBoxRoleMaster.SelectedItem != null;
            if (!valid_a) errorProviderUser.SetError(textBoxUserCode, "User Code can not be empty");
            if (!valid_b) errorProviderUser.SetError(textBoxUserName, "User Name can not be empty");
            if (!valid_c) errorProviderUser.SetError(textBoxPassword, "Password can not be empty");
            if (!valid_d) errorProviderUser.SetError(textBoxConfirmPassword, "Password is different");
            if (!valid_e) errorProviderUser.SetError(comboBoxRoleMaster, "Role can not be empty");
            return valid_a && valid_b && valid_c && valid_d && valid_e;
        }

        private void clearErrorProvider()
        {
            errorProviderUser.SetError(textBoxUserCode, "");
            errorProviderUser.SetError(textBoxUserName, "");
            errorProviderUser.SetError(textBoxPassword, "");
            errorProviderUser.SetError(textBoxConfirmPassword, "");
            errorProviderUser.SetError(comboBoxRoleMaster, "");
        }

        private void enableForm(bool enable)
        {
            textBoxUserName.ReadOnly = !enable;
            textBoxUserCode.ReadOnly = !enable;
            textBoxPassword.ReadOnly = !enable;
            textBoxConfirmPassword.ReadOnly = !enable;
            checkBoxActive.Enabled = enable;
            textBoxEmail.ReadOnly = !enable;
            dateTimePickerExpiry.Enabled = enable;
            comboBoxRoleMaster.Enabled = enable;
            checkBoxPasswordExpired.Enabled = enable;
        }

        void toolBarButtonClear_Click(object sender, EventArgs e)
        {
            clearForm();
            
        }

        private void clearForm()
        {
            textBoxUserName.Text = string.Empty;
            textBoxUserCode.Text = string.Empty;
            textBoxPassword.Text = string.Empty;
            textBoxConfirmPassword.Text = string.Empty;
            textBoxEmail.Text = string.Empty;
            dateTimePickerExpiry.Value = DateTime.Today.AddMonths(3);
            checkBoxPasswordExpired.Checked = true;
            comboBoxRoleMaster.SelectedIndex = 0;
            m_user = new User();
           // listViewRecords.SelectedItems.Clear();
            clearErrorProvider();
            enableForm(true);
            setEditMode(EditMode.Create);
            textBoxUserCode.SelectAll();
        }

        private void loadAllUser()
        {
            listViewRecords.Items.Clear();
            IList users = m_userService.LoadAllUser();
            foreach(User user in users)
            {
                ListViewItem item = listViewRecords.Items.Add(user.UserCode);
                item.SubItems.Add(user.UserName);
                item.Tag = user;
            }
        }

        private void loadUser()
        {
            m_user.Role = m_userService.GetRoleMasterByID(m_user.Role.RoleMasterID);
            textBoxUserName.Text = m_user.UserName;
            textBoxUserCode.Text = m_user.UserCode;
            textBoxPassword.Text = m_user.Password;
            textBoxConfirmPassword.Text = m_user.Password;
            textBoxEmail.Text = m_user.EmailID;
            checkBoxActive.Checked = m_user.ActiveCode;
            dateTimePickerExpiry.Value = m_user.ExpiryDate;
            checkBoxPasswordExpired.Checked = m_user.PasswordExpired;
            comboBoxRoleMaster.Text = m_user.Role.ToString();
        }

        private void listViewRecords_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewRecords.SelectedItem == null) return;
            m_user = (User)listViewRecords.SelectedItem.Tag;
            loadUser();
            enableForm(false);
            setEditMode(EditMode.Load);
        }

        public void LoadUserFromSearch(User user)
        {
            m_user = user;
            loadUser();
            enableForm(false);
            setEditMode(EditMode.Load);
        }

        private void comboBoxRoleMaster_Validating(object sender, CancelEventArgs e)
        {

        }
    }
}